package com.sunshine.wrongquestionset.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.Adapter
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.callback.OnListEmptyListener
import es.dmoral.toasty.Toasty
import org.jetbrains.annotations.NotNull

/**
 * @author sunshine
 * @date 2021/4/13
 */
class HasEmptyRecyclerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private val recyclerView: RecyclerView
    private val imageViewEmpty: ImageView

    /**
     * 设置布局
     */
    fun setLayoutManager(@NotNull layoutManager: RecyclerView.LayoutManager) {
        recyclerView.layoutManager = layoutManager
    }

    /**
     * 添加带有空回调的adapter
     */
    fun <VH : RecyclerView.ViewHolder?> setAdapter(adapter: HasEmptyRecyclerAdapter<VH>) {
        //每次初始化时判断初始化时的列表是否为空
        imageViewEmpty.visibility = if (adapter.listIsEmpty()) View.VISIBLE else View.GONE

        //该changed需要notify否则不会生效
        adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onChanged() {
                super.onChanged()
                imageViewEmpty.visibility = if (adapter.listIsEmpty()) View.VISIBLE else View.GONE
            }
        })

        recyclerView.adapter = adapter
    }

    init {
        LayoutInflater.from(context).inflate(R.layout.view_has_empty_recycler, this)

        recyclerView = rootView.findViewById(R.id.recyclerView_empty)
        imageViewEmpty = rootView.findViewById(R.id.imageView_empty)
    }
}